//
// Created by yuping.li on 10/24/24.
//

#ifndef PWM_DUTY_ADJUST_TASK_HPP_
#define PWM_DUTY_ADJUST_TASK_HPP_

#include "task.hpp"
#include "tim/pwm_generator.hpp"
#include "incubator/state_machine/fsm_incubatorfsm.h"

class PwmDutyAdjustTask : public Task {
 public:
  PwmDutyAdjustTask() {
    period_ms = 200U;
  }

  void init_task() override {
    fan_pwm = std::make_unique<PwmGenerator>(&htim3, TIM_CHANNEL_4);
    auto ret = fan_pwm->init();
    CCLOG(SWEN_INFO, "[TEST|PUT|FAN_PWM_INIT|%s]", (ret == HAL_OK) ? "PASS" : "FAIL");
    heater_pwm = std::make_unique<PwmGenerator>(&htim3, TIM_CHANNEL_3);
    ret = heater_pwm->init();
    CCLOG(SWEN_INFO, "[TEST|PUT|HEATER_PWM_INIT|%s]", (ret == HAL_OK) ? "PASS" : "FAIL");
  }

  void period_task() override {
    if (Rte::instance().incubator_mode == MODE_WORKING) {
//      Rte::instance().fan_duty = fan_pwm_adjust(Rte::instance().heater_temp, Rte::instance().target_temp);
      Rte::instance().heater_duty = heater_pwm_adjust(Rte::instance().current_temp, Rte::instance().target_temp);
      Rte::instance().fan_duty = Rte::instance().heater_duty;
    } else {
      Rte::instance().fan_duty = 0U;
      Rte::instance().heater_duty = 0U;
    }
    fan_pwm->set_duty(Rte::instance().fan_duty);
    heater_pwm->set_duty(Rte::instance().heater_duty);
  }

 protected:
  std::unique_ptr<PwmGenerator> fan_pwm{nullptr};
  std::unique_ptr<PwmGenerator> heater_pwm{nullptr};

  static uint32_t fan_pwm_adjust(int32_t heater_temp, int32_t target_temp) {
    if ((heater_temp - target_temp) < 50) {
      return 0U;
    }
    uint32_t duty = (heater_temp - target_temp) * 0.3;
    if (duty > 100) {
      duty = 100;
    }
    return duty;
  }

  static uint32_t heater_pwm_adjust(int32_t current_temp, int32_t target_temp) {
    if (((target_temp - current_temp) < 2) || (current_temp > target_temp)) {
      return 0U;
    }
    uint32_t duty = (target_temp - current_temp) * 2;
    if (duty > 100) {
      duty = 100;
    }
    return duty;
  }

};

#endif //PWM_DUTY_ADJUST_TASK_HPP_
